//app.js
//日志工具类打印控制
var mta = require('./utils/mta_analysis.js')
const isLog = true
App({
  onLaunch: function () {
    this.mta()
    //隐藏系统tabbar
    wx.hideTabBar()
    //获取系统信息
    this.getSystemInfo()
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.wxUserInfo = res.userInfo
              this.getUserInfo()
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        } else {
          console.error("用户未授权！")
        }
      }
    })
    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let capsule = wx.getMenuButtonBoundingClientRect();
        if (capsule) {
          this.globalData.Custom = capsule;
          this.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
        } else {
          this.globalData.CustomBar = e.statusBarHeight + 50;
        }
      }
    })
  },

  globalData: {
    //线上后台地址
     url: "https://www.xinwangzn.com/apinew/v2/",
    //请求地址 本地
    // url: "http://10.0.0.188:88/api/v2/",
    // url: "http://10.0.0.121:88/api/v2/",
    // url: "http://10.0.0.112:88/api/v2/",
    // url: "http://10.0.0.234:88/api/v2/",
    //url: "https://m.xinwangzn.com:8888/xwzn-api/v2/",
    // url: "http://112.19.161.232:8887/apinew/v2/", //测试服务器
    //上传文件地址  本地
    // upFileUrl: "http://10.0.0.28:90/fileservice/v1/fileYd",
    //可外网
    // upFileUrl: "http://112.19.161.232:89/fileservice/v1/fileYd",
    //线上文件服务
    upFileUrl: "https://www.xinwangzn.com/fileservice/v1/fileYd",
    //上传文件地址  (线上) 东升
    // upFileUrl: "https://zzdsjpt.cn:3369/fileserves/v1/fileYd",
    //区域编码
    areaCode: "86.51.01.08.10.02",
    //单位编码
    unitCode: "86.001.001.001.001.010.002",
    // unitCode: "86.001.001.001.009.003.001",
    //小程序ID
    appId: 'wx6794a7b33414287d',
    applet_id:'0021454121001219',//平台appid
    //平台用户信息
    userInfo: null,
    //平台小程序信息
    applet: null,
    //微信用户信息
    wxUserInfo: null,
    //入住房间id
    room_id: null,
    //用于判断是否登录
    accessToken: "",
    //用于token过期刷新accessToken
    refreshToken: "",
    //标题 注意(请在每个 js 里面加入动态设置标题的代码)
    appTitle: "白莲院坝里",
    //主题色配置
    theme: {
      themeColor: ["#E1C178", "#BABFC6", "#E9EAEC", "#52C41A", "#FF4D4F"], //主题颜色(从主题色->辅助色)
      titleColor: ["#161B23", "#878D93", "#838685", "#D8D8D8"], //标题颜色(从标题->分割线)
      titleSize: [40, 36, 32, 30], //标题字体大小(从大字体->小字体)
      contentSize: [30, 28, 26, 24, 20], //内容字体大小(从大字体->小字体)
      padding: [12, 24], //页面边距(从上下->左右距离
      btnHeight: [100, 60], //按钮高度(从大按钮->小按钮)
      btnTextSize: [40, 30], //按钮文字大小(从大字体->小字体)
      textSize: [12, 26, 36],//字体大小
      textColor: ["#202323"],//字体颜色
    },
    //系统信息
    systemInfo: null,
    //身份证照片地址
    cardImageUrl: null,
    cardInfo: null,
    //人脸照片地址
    peopleImageUrl: null,
    //判断是否直接跳转
    isAuthentication:false,
    pageNumber: 1,
    pageSize: 10,
    tabBar: {
      "color": "#838685",
      "selectedColor": "#E1C178",
      "backgroundColor": "#ffffff",
      "borderStyle": "black",
      "list": [{
        "pagePath": "/pages/index/index",
        "iconPath": "icon/home.png",
        "selectedIconPath": "icon/home_selected.png",
        "text": "首页"
      },
      {
        "pagePath": "/pages/community_worker/handle_to_unit",
        "iconPath": "icon/report.png",
        "selectedIconPath": "icon/report_selected.png",
        "text": "便民电话"
      },
      {
        "isSpecial": true,
        "pagePath": "/pages/event/event_report",
        "iconPath": "icon/icon_release.png",
        "text": "随手报"
      },
      {
        "pagePath": "/pages/service_more/service_more",
        "iconPath": "icon/shop.png",
        "selectedIconPath": "icon/shop_selected.png",
        "text": "社区生活"
      },
      {
        "pagePath": "/pages/mine/mine",
        "iconPath": "icon/my.png",
        "selectedIconPath": "icon/my_selected.png",
        "text": "我的"
      }
      ]
    }
  },

  /**
   * 编辑 tabBar
   */
  editTabBar: function () {
    //隐藏系统tabbar
    wx.hideTabBar({
      animation: true
    })
    let tabBar = this.globalData.tabBar;
    let currentPages = getCurrentPages();
    let _this = currentPages[currentPages.length - 1];
    let pagePath = _this.route;
    (pagePath.indexOf('/') != 0) && (pagePath = '/' + pagePath);
    for (let i in tabBar.list) {
      tabBar.list[i].selected = false;
      (tabBar.list[i].pagePath == pagePath) && (tabBar.list[i].selected = true);
    }
    _this.setData({
      tabBar: tabBar
    });
  },

  /**
   * 获取系统信息
   */
  getSystemInfo: function () {
    wx.getSystemInfo({
      success: (res) => {
        this.globalData.systemInfo = res;
      }
    });
  },

  /**
   * 平台用户登录
   * 微信用户授权后可以调用此方法直接登录平台
   * 使用方法：app.getUserInfo(res => { 成功执行的函数，res为请求成功结果 },err => { 失败执行的函数，err为请求失败结果 })
   * @param success 成功执行的函数,参数为请求结果  可空
   * @param fail 失败执行的函数,参数为请求结果  可空
   */
  getUserInfo: function (success, fail) {
    const _this = this
    const log = new this.appLogs()
    const http = new this.appHttp()
    wx.login({
      success: res => {
        //获取openId
        http.get("applet/user/openId", {
          appid: _this.globalData.appId,
          js_code: res.code
        }).then(res2 => {
          if (res2.data.code === http.REQUEST_OK) {
            //平台登录
            http.put("user/appletLogin", {
              applet_id: _this.globalData.appId,
              open_id: res2.data.data.openid,
              nickname: _this.globalData.wxUserInfo.nickName,
              head_img_url: _this.globalData.wxUserInfo.avatarUrl,
              sex: _this.globalData.wxUserInfo.gender
            }).then(res3 => {
              if (res3.data.code === http.REQUEST_OK) {
                _this.globalData.accessToken = res3.data.data.access_token
                _this.globalData.refreshToken = res3.data.data.refresh_token
                _this.globalData.userInfo = res3.data.data.user
                _this.globalData.applet = res3.data.data.applet
                if (success != null) {
                  success(res3)
                }
                http.get("room/default", {
                  people_id: res3.data.data.user.people_id,
                  applet_id: res3.data.data.user.applet_id,
                }).then((res4) => {
                  _this.globalData.room_id = res4.data.data.roomId
                })
                //埋点
                http.postJson("user/area/associate", {
                  user_id: _this.globalData.userInfo == null ? '' : _this.globalData.userInfo.applet_user_id,
                  area_code: _this.globalData.areaCode
                }).then(res => { }, err => { })
              } else {
                log.e("登录失败！")
                if (fail != null) {
                  fail(res3)
                }
              }
            }, err => {
              if (fail != null) {
                fail(err)
              }
            })
          } else {
            log.e("登录失败！")
            if (fail != null) {
              fail(res2)
            }
          }
        }, err => {
          if (fail != null) {
            fail(err)
          }
        })
      }
    })
  },

  /**
   * 保存选择的社区信息
   * @param name 社区名称 用于标题
   * @param areaCode 区域码
   * @param unitCode
   */
  saveCommunity: function (name, areaCode, unitCode) {
    const community = {
      name: name,
      areaCode: areaCode,
      unitCode: unitCode
    }
    try {
      wx.setStorageSync("community", community)
      console.log("保存成功")
    } catch (e) {
      console.error(e)
    }
  },

  /**
   * 获取本地保存的社区信息
   * @param success 获取数据成功的回调，res为成功回调结果
   * @param fail 获取数据失败的回调，err为失败回调结果 ( 没有数据也是调用此回调 )
   */
  getCommunity: function (success, fail) {
    wx.getStorage({
      key: "community",
      success: res => {
        if (success != null) {
          success(res)
        }
      },
      fail: err => {
        if (fail != null) {
          fail(err)
        }
      }
    })
  },

  /**
   * 判断是否已经登录跳转页面
   * @param url 目标地址
   */
  isLogin: function (url) {
    if (this.globalData.userInfo != null) {
      wx.navigateTo({
        url: url,
      })
    } else {
      wx.navigateTo({
        url: '/pages/mine/login/login',
      })
    }
  },

  /**
   * 身份证验证
   * @param num
   * @return {boolean}
   */
  isCardNo(num) {
    var factorArr = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1);
    var parityBit = new Array("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2");
    var varArray = new Array();
    var intValue;
    var lngProduct = 0;
    var intCheckDigit;
    var intStrLen = num.length;
    var idNumber = num;
    // initialize
    if ((intStrLen != 15) && (intStrLen != 18)) {
      return false;
    }
    // check and set value
    for (let i = 0; i < intStrLen; i++) {
      varArray[i] = idNumber.charAt(i);
      if ((varArray[i] < '0' || varArray[i] > '9') && (i != 17)) {
        return false;
      } else if (i < 17) {
        varArray[i] = varArray[i] * factorArr[i];
      }
    }

    if (intStrLen == 18) {
      //check date
      var date8 = idNumber.substring(6, 14);
      if (this.isDate8(date8) == false) {
        return false;
      }
      // calculate the sum of the products
      for (let i = 0; i < 17; i++) {
        lngProduct = lngProduct + varArray[i];
      }
      // calculate the check digit
      intCheckDigit = parityBit[lngProduct % 11];
      // check last digit
      if (varArray[17] != intCheckDigit) {
        return false;
      }
    }
    else {        //length is 15
      //check date
      var date6 = idNumber.substring(6, 12);
      if (this.isDate6(date6) == false) {
        return false;
      }
    }
    return true;
  },
  /**
   * 身份证验证相关函数
   * @param sDate
   * @return {boolean}
   */
  isDate6: function(sDate) {
    if (!/^[0-9]{6}$/.test(sDate)) {
      return false;
    }
    var year, month, day;
    year = sDate.substring(0, 4);
    month = sDate.substring(4, 6);
    if (year < 1700 || year > 2500) return false
    if (month < 1 || month > 12) return false
    return true
  },
  /**
   * 身份证验证相关函数
   * @param sDate
   * @return {boolean}
   */
  isDate8: function(sDate) {
    if (!/^[0-9]{8}$/.test(sDate)) {
      return false;
    }
    var year, month, day;
    year = sDate.substring(0, 4);
    month = sDate.substring(4, 6);
    day = sDate.substring(6, 8);
    var iaMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if (year < 1700 || year > 2500) return false
    if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) iaMonthDays[1] = 29;
    if (month < 1 || month > 12) return false
    if (day < 1 || day > iaMonthDays[month - 1]) return false
    return true
  },

  /**
   * 日志打印工具类
   * 使用方法:
   * const log = new app.appLogs()
   * log.l(msg)
   */
  appLogs: function () {
    /**
     * 打印普通日志
     * @param msg
     * @param optionalParams
     */
    this.l = function (msg, optionalParams) {
      if (isLog) {
        if (optionalParams === undefined) {
          console.log(msg)
        } else {
          console.log(msg, optionalParams)
        }
      }
    }
    /**
     * 打印 Error 日志
     * @param msg
     * @param optionalParams
     */
    this.e = function (msg, optionalParams) {
      if (isLog) {
        if (optionalParams === undefined) {
          console.error(msg)
        } else {
          console.error(msg, optionalParams)
        }
      }
    }
    /**
     * 打印 info 日志
     * @param msg
     * @param optionalParams
     */
    this.i = function (msg, optionalParams) {
      if (isLog) {
        if (optionalParams === undefined) {
          console.info(msg)
        } else {
          console.info(msg, optionalParams)
        }
      }
    }
    /**
     * 打印 Debug 日志
     * @param msg
     * @param optionalParams
     */
    this.d = function (msg, optionalParams) {
      if (isLog) {
        if (optionalParams === undefined) {
          console.debug(msg)
        } else {
          console.debug(msg, optionalParams)
        }
      }
    }
  },

  /**
   * 网络请求工具类
   * 使用方法 const http = new app.appHttp()
   * http.get(地址,参数).then(成功 =>{
   *     成功处理
   * },失败 =>{
   *     失败处理
   * })
   */
  appHttp: function () {
    const app = getApp()
    const log = new app.appLogs()
    const _this = this

    this.REQUEST_OK = 200

    /**
     * Get 方法
     * @param url 请求地址
     * @param data 请求参数
     */
    this.get = function (url, data) {
      return this.promise('GET', url, null, data)
    }
    /**
     * Get 方法 微服务
     * @param url
     * @param data
     */
    this.getMicro = function (url, data) {
      return this.promiseMicro('GET', url, null, data)
    }
    this.getJson = function (url, data) {
      return this.promise('GET', url, {
        'Authorization': app.globalData.accessToken
      }, data)
    }
    /**
     * Get 方法 可自定义 header
     * @param url
     * @param header
     * @param data
     */
    this.getHeader = function (url, header, data) {
      return this.promise('GET', url, header, data)
    }
    /**
     * Get 方法 微服务
     * @param url
     * @param header
     * @param data
     */
    this.getMicroHeader = function (url, header, data) {
      return this.promiseMicro('GET', url, header, data)
    }

    /**
     * Post 方法
     * @param url 请求地址
     * @param data 请求参数
     */
    this.post = function (url, data) {
      return this.promise('POST', url, null, data)
    }
    this.postMicro = function (url, data) {
      return this.promiseMicro('POST', url, null, data)
    }
    this.postJson = function (url, data) {
      return this.promise('POST', url, {
        'Authorization': app.globalData.accessToken
      }, data)
    }
    /**
     * Post 方法 可自定义 header
     * @param url 请求地址
     * @param header 请求头
     * @param data 请求参数
     */
    this.postHeader = function (url, header, data) {
      return this.promise('POST', url, header, data)
    }
    this.postHeaderMicro = function (url, header, data) {
      return this.promiseMicro('POST', url, header, data)
    }

    /**
     * Put 方法
     * @param url 请求地址
     * @param data 请求参数
     */
    this.put = function (url, data) {
      return this.promise('PUT', url, null, data)
    }
    this.putMicro = function (url, data) {
      return this.promiseMicro('PUT', url, null, data)
    }
    this.putJson = function (url, data) {
      return this.promise('PUT', url, {
        'Authorization': app.globalData.accessToken
      }, data)
    }
    /**
     * Put 方法 可自定义 header
     * @param url 请求地址
     * @param header 请求头
     * @param data 请求参数
     */
    this.putHeader = function (url, header, data) {
      return this.promise('PUT', url, header, data)
    }
    this.putHeaderMicro = function (url, header, data) {
      return this.promiseMicro('PUT', url, header, data)
    }
    /**
     * Delete 方法
     * @param url 请求地址
     * @param data 请求参数
     */
    this.delete = function (url, data) {
      return this.promise('DELETE', url, null, data)
    }
    this.deleteMicro = function (url, data) {
      return this.promiseMicro('DELETE', url, null, data)
    }
    this.deleteJson = function (url, data) {
      return this.promise('DELETE', url, {
        'Authorization': app.globalData.accessToken
      }, data)
    }
    /**
     * Delete 方法
     * @param url 请求地址
     * @param header 请求头
     * @param data 请求参数
     */
    this.deleteHeader = function (url, header, data) {
      return this.promise('DELETE', url, header, data)
    }
    this.deleteHeaderMicro = function (url, header, data) {
      return this.promiseMicro('DELETE', url, header, data)
    }
    /**
     * Promise 实现
     * @param method 请求方法
     * @param url 请求地址
     * @param header 请求头
     * @param data 请求参数
     * @returns Promise 返回结果
     */
    this.promise = function (method, url, header, data) {
      return new Promise(((resolve, reject) => {
        //获取网络类型
        wx.getNetworkType({
          success: res => {
            if (res.networkType !== "none") {
              if (data === undefined || data == null) {
                data = {}
              }
              try { } catch (e) { }
              _this.request(method, url, header, data, resolve, reject)
            } else {
              log.l("没有连接到网络")
              wx.showToast({
                title: '网络连接失败',
                icon: "none",
                duration: 3000
              })
            }
          }
        })
      }))
    }

    /**
     * Promise 实现  微服务
     * @param method 请求方法
     * @param url 请求地址
     * @param header 请求头
     * @param data 请求参数
     * @returns Promise 返回结果
     */
    this.promiseMicro = function (method, url, header, data) {
      return new Promise(((resolve, reject) => {
        //获取网络类型
        wx.getNetworkType({
          success: res => {
            if (res.networkType !== "none") {
              if (data === undefined || data == null) {
                data = {}
              }
              try { } catch (e) { }
              _this.requestMicro(method, url, header, data, resolve, reject)
            } else {
              log.l("没有连接到网络")
              wx.showToast({
                title: '网络连接失败',
                icon: "none",
                duration: 3000
              })
            }
          }
        })
      }))
    }

    /**
     * 刷新 token
     * 成功返回新 token 失败返回 null
     */
    this.refreshToken = async function () {
      wx.request({
        method: 'GET',
        url: app.globalData.url + "/user/token",
        header: {
          refresh_token: app.globalData.refreshToken
        },
        success: res => {
          log.l(JSON.stringify(res))
          if (res.data.code === _this.REQUEST_OK) {
            return res.data.data
          }
          return null
        },
        fail: res => {
          log.e(JSON.stringify(res))
          return null
        }
      })
    }

    /**
     * 请求方法
     * @param method 请求方法 GET,POST,PUT,DELETE
     * @param url 请求地址
     * @param header 可空，为空则默认
     * @param data 请求参数
     * @param resolve 请求成功处理
     * @param reject 请求失败处理
     */
    this.request = function (method, url, header, data, resolve, reject) {
      let head = header
      if (header === null || header === undefined) {
        head = {
          'content-type': 'application/x-www-form-urlencoded',
          'Authorization': app.globalData.accessToken
        }
      }
      log.l("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓")
      log.l('<!------------[ ' + url + ' ]------------------------------------------------')
      log.l("请求方法: " + method)
      log.l("请求地址: " + app.globalData.url + url)
      log.l("请求头部: " + JSON.stringify(head))
      log.l("请求参数: " + JSON.stringify(data))
      wx.request({
        method: method,
        url: app.globalData.url + url,
        header: head,
        data: data,
        success: res => {
          if (res.statusCode === 200) {
            try {
              log.l("请求结果: " + JSON.stringify(res))
              log.l('--------------[ ' + url + ' ]------------------------------------------------>')
              log.l('↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑')
              resolve(res)
            } catch (e) { }
          } else {
            log.e("请求结果: " + JSON.stringify(res))
            log.e('--------------[ ' + url + ' ]------------------------------------------------>')
            reject(res)
          }
        },
        fail: res => reject(res)
      });
    }

    /**
     *  微服务请求
     * @param method 请求方法 GET,POST,PUT,DELETE
     * @param url 请求地址
     * @param header 可空，为空则默认
     * @param data 请求参数
     * @param resolve 请求成功处理
     * @param reject 请求失败处理
     */
    this.requestMicro = function (method, url, header, data, resolve, reject) {
      let head = header
      if (header === null || header === undefined) {
        head = {
          'content-type': 'application/x-www-form-urlencoded',
          'Authorization': app.globalData.accessToken
        }
      }
      log.l("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓")
      log.l('<!------------[ ' + url + ' ]------------------------------------------------')
      log.l("请求方法: " + method)
      log.l("请求地址: " + app.globalData.urlMicro + url)
      log.l("请求头部: " + JSON.stringify(head))
      log.l("请求参数: " + JSON.stringify(data))
      wx.request({
        method: method,
        url: app.globalData.urlMicro + url,
        header: head,
        data: data,
        success: res => {
          if (res.statusCode === 200) {
            try {
              log.l("请求结果: " + JSON.stringify(res))
              log.l('--------------[ ' + url + ' ]------------------------------------------------>')
              log.l('↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑')
              resolve(res)
            } catch (e) { }
          } else {
            log.e("请求结果: " + JSON.stringify(res))
            log.e('--------------[ ' + url + ' ]------------------------------------------------>')
            reject(res)
          }
        },
        fail: res => reject(res)
      });
    }

    /**
     * 上传文件
     * @param file 上传文件的地址
     * @param savePath 保存在服务器上的路径
     */
    this.upFile = function (file, savePath) {
      return new Promise((resolve, reject) => {
        //获取网络类型
        wx.getNetworkType({
          success: res => {
            if (res.networkType !== "none") {
              let type = file.substr(file.lastIndexOf("."))
              if (type == ".jpg") {
                wx.compressImage({
                  src: file,
                  success: compressRes => {
                    file = compressRes.tempFilePath
                    log.e("压缩成功" )
                    const uploadTask = wx.uploadFile({
                      url: app.globalData.upFileUrl,
                      filePath: file,
                      name: 'file',
                      formData: {
                        filePath: savePath
                      },
                      success: res => {
                        try {
                          const data = JSON.parse(res.data)
                          resolve(data)
                          log.l("上传文件成功：" + JSON.stringify(data))
                        } catch (e) {
                          resolve(res)
                          log.l("上传文件成功：" + JSON.stringify(res))
                        }

                      },
                      fail: res => {
                        try {
                          const data = JSON.parse(res.data)
                          reject(data)
                          log.e("上传文件失败：" + JSON.stringify(data))
                        } catch (e) {
                          reject(res)
                          log.e("上传文件失败：" + JSON.stringify(res))
                        }
                      }
                    })
                    uploadTask.onProgressUpdate(res => {
                      // log.l(JSON.stringify(res))
                    })
                  },
                  fail: compressErr =>{
                    const uploadTask = wx.uploadFile({
                      url: app.globalData.upFileUrl,
                      filePath: file,
                      name: 'file',
                      formData: {
                        filePath: savePath
                      },
                      success: res => {
                        try {
                          const data = JSON.parse(res.data)
                          resolve(data)
                          log.l("上传文件成功：" + JSON.stringify(data))
                        } catch (e) {
                          resolve(res)
                          log.l("上传文件成功：" + JSON.stringify(res))
                        }

                      },
                      fail: res => {
                        try {
                          const data = JSON.parse(res.data)
                          reject(data)
                          log.e("上传文件失败：" + JSON.stringify(data))
                        } catch (e) {
                          reject(res)
                          log.e("上传文件失败：" + JSON.stringify(res))
                        }
                      }
                    })
                    uploadTask.onProgressUpdate(res => {
                      // log.l(JSON.stringify(res))
                    })
                  }
                })
              }else {
                const uploadTask = wx.uploadFile({
                  url: app.globalData.upFileUrl,
                  filePath: file,
                  name: 'file',
                  formData: {
                    filePath: savePath
                  },
                  success: res => {
                    try {
                      const data = JSON.parse(res.data)
                      resolve(data)
                      log.l("上传文件成功：" + JSON.stringify(data))
                    } catch (e) {
                      resolve(res)
                      log.l("上传文件成功：" + JSON.stringify(res))
                    }

                  },
                  fail: res => {
                    try {
                      const data = JSON.parse(res.data)
                      reject(data)
                      log.e("上传文件失败：" + JSON.stringify(data))
                    } catch (e) {
                      reject(res)
                      log.e("上传文件失败：" + JSON.stringify(res))
                    }
                  }
                })
                uploadTask.onProgressUpdate(res => {
                  // log.l(JSON.stringify(res))
                })
              }
            } else {
              log.l("没有连接到网络")
              wx.showToast({
                title: '网络连接失败',
                icon: "none",
                duration: 3000
              })
              const failData = {
                code: 400,
                msg: '网络连接失败'
              }
              reject(failData)
            }
          }
        })
      })
    }

  },
  mta: function () {
    mta.App.init({
      "appID": "500730301",
      "autoReport": true,
      "statParam": true,
      "ignoreParams": [],
    });
  },
    /**
     * 坐标转换 ，高德转百度
     */
    gaoDeToBaidu: function (gd_longitude, gd_latitude) {
      let PI = 3.14159265358979324 * 3000.0 / 180.0;
      let x = gd_longitude, y = gd_latitude;
      let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * PI);
      let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * PI);
      let longitude = z * Math.cos(theta) + 0.0065;//经度
      let latitude = z * Math.sin(theta) + 0.006;//纬度
      return { longitude, latitude };
  },
})